package com.sdau.repairmaster.UIFile.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sdau.repairmaster.R;
import com.sdau.repairmaster.UIFile.adapter.MyRecycleViewAdapter;
import com.sdau.repairmaster.logic.model.RepairInfo;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.Context.MODE_PRIVATE;
import static android.os.Build.VERSION.SDK_INT;

public class SecondFragment extends Fragment {

    private final int FAILURE_CODE = 1001;//失败
    private final int SUCCESS_CODE = 1000;//成功

    private List<RepairInfo> repairInfoList = new ArrayList<>();
    private RecyclerView rvHistory;
    private String listJson = null;

    private SharedPreferences pref;
    private SharedPreferences.Editor editor;


    private TextView mFreshText;
    private SwipeRefreshLayout swipeRefreshLayout;

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCESS_CODE://成功
                    String data = (String) msg.obj;
                    Log.d("MIN", data);
                    if (data!=null && !"".equals(data.trim()))
                        uploadListSuccess(data);
                    else
                        uploadListFailed();
                    break;
                case FAILURE_CODE://失败
                    Toast.makeText(getContext(),"网络异常",Toast.LENGTH_SHORT).show();
                    break;

            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_second, container, false);
        swipeRefreshLayout = view.findViewById(R.id.refresh_layout);
        rvHistory = view.findViewById(R.id.history);
        mFreshText = view.findViewById(R.id.tv_pull_down_refresh);

        initRepairInfo();

        System.out.println(repairInfoList);
        for(RepairInfo repairInfo:repairInfoList){
            System.out.println(repairInfo);
        }
        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvHistory.setLayoutManager(linearLayoutManager);

        //设置分割线
        rvHistory.addItemDecoration(new Liner());

        //设置适配器

        return view;
    }

    private void initRepairInfo() {
        //获取保存的账号
        SharedPreferences pref = getActivity().getSharedPreferences("data",MODE_PRIVATE);
        String account = pref.getString("account", "-1");
        Log.d("RRRRRR: ",account);
        Adapter();//
        uploadRepairInfoList("2018512648");


        /*
        for (int i = 0; i < 5; ++i) {
            RepairInfo repairInfo1 = new RepairInfo();
            repairInfo1.setType("1");
            repairInfo1.setDescribe("1111111");
            repairInfo1.setTime("111111");
            repairInfoList.add(repairInfo1);

            RepairInfo repairInfo2 = new RepairInfo();
            repairInfo2.setType("2");
            repairInfo2.setDescribe("2211111112");
            repairInfo2.setTime("222222");
            repairInfoList.add(repairInfo2);

            RepairInfo repairInfo3 = new RepairInfo();
            repairInfo3.setType("3");
            repairInfo3.setDescribe("331113");
            repairInfo3.setTime("333333");
            repairInfoList.add(repairInfo3);
        }
         */
    }


    public SecondFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param
     * @param
     * @return A new instance of fragment SpeechFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SecondFragment newInstance() {
        SecondFragment fragment = new SecondFragment();

        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    //分割线
    class Liner extends RecyclerView.ItemDecoration {
        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(0, 0, 0, getResources().getDimensionPixelOffset(R.dimen.liner));
        }
    }


    public void uploadRepairInfoList(final String account) {
        new Thread(
                new Runnable() {
                    @Override
                    public void run() {

                        final String URL_uploadList = "http://10.0.2.2:8080/RepairAdmin/repairInfoServlet";
                        final Message message = Message.obtain();

                        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                                .connectTimeout(10, TimeUnit.SECONDS)
                                .writeTimeout(10, TimeUnit.SECONDS)
                                .readTimeout(20, TimeUnit.SECONDS)
                                .build();


                        RequestBody requestBody = new FormBody.Builder()
                                .add("account", account)
                                .add("flag", "uploadRepairInfoList")
                                .build();


                        final OkHttpClient client = new OkHttpClient();
                        final Request request = new Request.Builder()
                                .url(URL_uploadList)
                                .post(requestBody)
                                .build();


                        client.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                                message.what = FAILURE_CODE;
                                message.obj = e.getMessage();//失败的信息
                                handler.sendMessage(message);
                            }

                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                String data = response.body().string();
                                message.what = SUCCESS_CODE;
                                message.obj = data;
                                handler.sendMessage(message);

                            }
                        });

                    }
                }
        ).start();
    }

    public void uploadListSuccess(String listJson){
        Gson gson = new Gson();
        repairInfoList = gson.fromJson(listJson,  new TypeToken<List<RepairInfo>>() {}.getType());
        MyRecycleViewAdapter myRecycleViewAdapter = new MyRecycleViewAdapter(repairInfoList,getContext(),null);
        rvHistory.setAdapter(myRecycleViewAdapter);
        rvHistory.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
        handleDownPullUpdate();
    }

    public void uploadListFailed(){

    }
    public void Adapter(){

        if (SDK_INT < Build.VERSION_CODES.P) {
            return;
        }
        try {
            Method forName = Class.class.getDeclaredMethod("forName", String.class);
            Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class);
            Class<?> vmRuntimeClass = (Class<?>) forName.invoke(null, "dalvik.system.VMRuntime");
            Method getRuntime = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "getRuntime", null);
            Method setHiddenApiExemptions = (Method) getDeclaredMethod.invoke(vmRuntimeClass, "setHiddenApiExemptions", new Class[]{String[].class});
            Object sVmRuntime = getRuntime.invoke(null);
            setHiddenApiExemptions.invoke(sVmRuntime, new Object[]{new String[]{"L"}});
        } catch (Throwable e) {
            Log.e("[error]", "reflect bootstrap failed:", e);
        }
    }

    class MyDecoration extends RecyclerView.ItemDecoration {
        @Override
        public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state)
        {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(0, 0, 0, getResources().getDimensionPixelOffset(R.dimen.dividerHeight));
        }
    }

    public void handleDownPullUpdate(){
        swipeRefreshLayout.setEnabled(true);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent,R.color.colorPrimary);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //被刷新时的操作
                //更新UI
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        initRepairInfo();
                        Toast.makeText(getContext() , "刷新成功！", Toast.LENGTH_SHORT).show();
                        swipeRefreshLayout.setRefreshing(false);
                    }
                },2000);
            }
        });
    }
}


